const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const path = require("path");

// 应用实例化
const app = express();
// 导入路由模块
const user = require("./router/user");
const file = require("./router/file");
const share = require("./router/share");
const getShareFiles = require("./router/getShareFiles");
const log = require("./router/log");
const apiUser = require("./router/apiUser");
// 导入jwt验证模块
// const auth = require("./utils/auth-jwt");
const { verify } = require("./utils/auth-jwt"); // 引入jwt认证函数

/* -----------配置------- */

// json中间件
app.use(bodyParser.json());
// 表单数据
app.use(bodyParser.urlencoded({ extended: false }));
// 跨域
app.use(cors());

// 托管前端代码
app.use("/", express.static(path.join(__dirname, "www/dist")));
// api文档
app.use("/doc", express.static(path.join(__dirname, "public/apidoc")));
// 默认图片
app.use("/imgs", express.static(path.join(__dirname, "public/imgs")));
// 上传的静态资源
app.use("/temporary/target", express.static(path.join(__dirname, "target")));
// 上传的静态资源
app.use("/users", express.static(path.join(__dirname, "public/users")));

// 注册，登录模块
app.use(user);
// 获取分享文件模块
app.use(getShareFiles);
//注册jwt验证中间件
app.use(verify);
//需要验证的接口模块
app.use("/api", file);
app.use("/api", share);
app.use("/api", log);
app.use("/api", apiUser);
// 错误中间件
app.use((err, req, res, next) => {
  // console.log("err===", err);
  const { output } = err || {};
  // 错误码和错误信息
  const errCode = (output && output.statusCode) || 500;
  const errMsg =
    (output && output.payload && output.payload.error) || err.message;
  res.status(errCode).json({
    code: errCode,
    msg: errMsg,
  });
});

const outPrint = `Server is running at http://localhost:8080`;

app.listen("8080", () => console.log(outPrint));
